let express = require('express');
let mysql = require('mysql');
let router = express.Router();
const jwt = require('jsonwebtoken');
const secretKey = 'vue-login';
let connection = mysql.createConnection({
    host : 'localhost',
    user:'root',
    password : 'root',
    database : 'express'
});
connection.connect((err) => {
    if (err) throw err;
    console.log('连接成功')
});
router.post('/login', (req, res) => {
    const { username, password } = req.body;
    console.log('req', req.body);
    const tokenStr = jwt.sign({
            username : username
        }, secretKey,{
            expiresIn : "0.1h"
        });
    let sql = `select * from user where username = '${username}'`;
    connection.query(sql,(err,result) => {
        if (err) {
            console.log('error',err);
        } else {
            if (result.length == 0){
                res.json({
                    status : 100,
                    msg : '请先注册!'
                });
            }else if (password == result[0].password){
                let dataString = JSON.stringify(result);
                let data = JSON.parse(dataString);
                res.json({
                    status : 200,
                    data ,
                    token : tokenStr
                })
            } else  if (password !== result[0].password) {
                res.json({
                    status : 101,
                    msg : '密码错误！'
                })
            }
        }
    });
})
module.exports = router;
